package com.hliushi.learn.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName MyFastJsonConfig
 * @Description 使用fastJson处理空值
 * @Author hliushi
 * @Date 2021/7/5 20:51
 * @Version V1.0
 **/
// @Configuration
public class FastJsonConfig extends WebMvcConfigurationSupport {

    /**
     * 使用fastJson时, 对null的处理和Jackson有所不同, 配置类需要继承WebMvcConfigurationSupport类
     * 然后覆盖configureMessageConverters方法, 在方法中, 我们可以选择要对实现null转换的场景, 配置好即可
     */


    /**
     * 使用阿里 FastJson 作为JSON MessageConverter
     *
     * @param converters
     */
    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

        com.alibaba.fastjson.support.config.FastJsonConfig config = new com.alibaba.fastjson.support.config.FastJsonConfig();

        config.setSerializerFeatures(
                // 保留map空的字段
                SerializerFeature.WriteMapNullValue,
                // 将String类型的null转为""
                SerializerFeature.WriteNullStringAsEmpty,
                // 将Number类型的null转为0
                SerializerFeature.WriteNullNumberAsZero,
                // 将List类型的null转为[]
                SerializerFeature.WriteNullListAsEmpty,
                // 将Boolean类型的null转为false
                SerializerFeature.WriteNullBooleanAsFalse,
                // 避免循环应用
                SerializerFeature.DisableCircularReferenceDetect
        );

        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(StandardCharsets.UTF_8);
        List<MediaType> mediaTypeList = new ArrayList<>();

        // 解决中文乱码问题, 相当于在Controller上的@RequestMapping汇总加了属性producers = "/application/json"
        mediaTypeList.add(MediaType.APPLICATION_JSON);
        converter.setSupportedMediaTypes(mediaTypeList);
        converters.add(converter);
    }
}
